package org.fude.bootstrap.controller;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

import javax.servlet.http.HttpSession;

import org.fude.dao.AchievementMapper;
import org.fude.entity.Achievement;
import org.fude.entity.User;
import org.fude.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/money")
public class MoneyController {
	Logger logger = LoggerFactory.getLogger(MoneyController.class);
	@Autowired
	AchievementMapper achMapper;
	@Autowired
    private HttpSession session;
	@Autowired
	ThreadPoolTaskScheduler sch;
	@Autowired
	Map<String,ScheduledFuture<?>> schMap;
	@PostMapping("")
	public boolean add(Achievement achieve) throws Exception {
		Date date = achieve.getOdate();
		achieve.setOyear(DateUtil.getYear(date));
		achieve.setOmonth(DateUtil.getMonth(date));
		User user = (User) session.getAttribute("user");
		achieve.setUser(user);
		achMapper.addAchieve(achieve);
		return true;
	}
	
	@RequestMapping("/cron")
	public boolean cron(String cron, String id) throws Exception {
		Assert.notNull(cron, "express is null");
		Assert.notNull(id, "id is null");
		crondl(id);
		
		ScheduledFuture<?> future = sch.schedule(new Runnable() {
			CronSequenceGenerator sequenceGenerator = new CronSequenceGenerator(cron);
			@Override
			public void run() {
				Date date = new Date();
				Date nextDate = sequenceGenerator.next(date);
				logger.info("Date {}", nextDate);
			}
		}, new CronTrigger(cron));
		schMap.put(id, future);
		return true;
	}
	@RequestMapping("/cronDelete")
	public boolean crondl(String id) throws Exception {
		if(schMap.containsKey(id)) {
			ScheduledFuture<?> ft = schMap.get(id);
			ft.cancel(true);
		}
		return true;
	}
	@RequestMapping("/cronUpdate")
	public boolean cronUpdate(String id,String cron) throws Exception {
		crondl(id);
		ScheduledFuture<?> future = sch.schedule(new Runnable() {
			CronSequenceGenerator sequenceGenerator = new CronSequenceGenerator(cron);
			@Override
			public void run() {
				Date date = new Date();
				Date nextDate = sequenceGenerator.next(date);
				logger.info("Date {}", nextDate);
			}
		}, new CronTrigger(cron));
		schMap.put(id, future);
		return true;
	}
}
